#!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime
from enum import IntEnum
import pandas as pd
import os
import time

import domain.transaction_data.repository.impl.cvs_repository as cvsRepository
from core.enums import Period
from domain.transaction_data.spider import tushare_spider
from infrastructure.util import dateutils
from infrastructure.util.dateutils import DateFormat
from config.config import config

def cvs_reader_only(path):
    assert os.path.exists(path)
    return pd.read_csv(path)


def cvs_reader(path, index_col='date_index', parse_dates=["date_index"]) -> pd.DataFrame:
    return pd.read_csv(path, index_col=index_col, parse_dates=parse_dates)


def cvs_write(path, df: pd.DataFrame):
    df.to_csv(path_or_buf=path)


def get_stock_transaction_data(ts_code, period:Period = Period.day, endTime: datetime.datetime = None) -> pd.DataFrame:
    return cvsRepository.get_stock_transaction_data(ts_code, period, endTime)


def realtimeQuote(security: str) -> pd.Series:
    return cvsRepository.realtimeQuote(security)


def get_stock_cur_transaction_data(ts_code) -> pd.DataFrame:
    return _get_transaction_data_by_tushare(ts_code)


def _get_transaction_data_by_tushare(ts_code, download=True, update=False) -> pd.DataFrame:
    """
    获取包含最新数据的股票交易数据，以日为单位
    :param ts_code:
    :return:
    """
    path = config.get('data', 'folder') + os.sep + "day" + os.sep + ts_code + ".csv"
    try:
        df = cvs_reader_only(path).sort_index(ascending=True)  # type:pd.DataFrame
        date = df['trade_date'].tolist()[-1]
    except:
        date = 0
        df = pd.DataFrame()
    if not df.empty and not update:
        df.set_index(keys='date_index', inplace=True)
        df = df.sort_index(ascending=True)
        return df
    if df.empty and not download:
        return df
    to_update = False
    lastest_transaction_dateStr = dateutils.getLastestTradingDate(time.strftime(DateFormat.Y_m_d.value), DateFormat.Y_m_d).replace('-', '')
    laster_transaction_dateStr = dateutils.getLastestTradingDate(
        dateutils.get_dateStr_before_num_days_by_dateStr(1, lastest_transaction_dateStr, dateFormat=DateFormat.Ymd), dateFormat=DateFormat.Ymd)
    if date < int(lastest_transaction_dateStr) and (int(time.strftime('%Y%m%d%H%M%S')) > int(
            lastest_transaction_dateStr + '150000') or date <= int(laster_transaction_dateStr)):
        df = tushare_spider.daily_data(ts_code=ts_code)  # type:pd.DataFrame
        to_update = True
    df['date_index'] = pd.to_datetime(df['trade_date'], format=dateutils.DateFormat.Ymd)
    df.set_index(keys='date_index', inplace=True)
    df = df.sort_index(ascending=True)
    if not df.empty and to_update:
        df.to_csv(path)
    return df

if __name__ == "__main__":
    path = config.get('data', 'folder') + os.sep + "day" + os.sep + "002044.SZ" + ".csv"
    df = cvs_reader(path)
    print(df['2005-07-10':'2005-07-10'])
